import {
    View, Text, Dimensions, Image, TouchableOpacity, DrawerLayoutAndroid,
    RefreshControl, FlatList, StyleSheet, TouchableHighlight, Alert,
} from 'react-native';
import React, {Component} from 'react';
import LocalImg from '../const/Images'
import Urls, {getRealUrl} from "../const/Urls";
import moment from 'moment/moment';
import {Button, List, InputItem} from 'antd-mobile-rn'

const {width, height} = Dimensions.get("window");

/**
 * 船况记录
 */
class PageCkjl extends Component {


    constructor(props) {
        super(props);
        this.user = this.props.user;
        this.isLoadMore = true;
        this.pageNum =  1;
        this.state = {
            shzt: 2,
            zwcm: '',
            ywcm: '',
            hh: '',
            imo: '',
            mmsi: '',
            data: [],
            isLoading: true,
        }
    }

    componentDidMount() {
        this.pageNum = 1;
        this.setState({
            data: [],
        });
        this.isLoadMore = true;
        this.loadData();
    }


    render() {

        return (

            <DrawerLayoutAndroid
                ref="drawer"
                renderNavigationView={() => this.renderSlideBar()}
                drawerWidth={300}
                drawerPosition={DrawerLayoutAndroid.positions.Right}>

                {this.renderHead()}
                {this.renderBody()}

            </DrawerLayoutAndroid>
        )
    }

    renderHead() {
        return (

            <View style={{
                flexDirection: 'row',
                flex: 0,
                height: 60,
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: '#0066FF'
            }}>
                <View style={{flex: 1, padding: 10}}>
                    <TouchableOpacity onPress={() => this.props.navigation.pop()}>
                        <Image source={LocalImg['backImg']} style={{height: 30, width: 30, resizeMode: 'contain'}}/>
                    </TouchableOpacity>
                </View>
                <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                    <Text style={{fontSize: 20, color: '#ffffff'}}>船况记录</Text>
                </View>

                <View style={{flex: 1, alignItems: 'flex-end', padding: 10}}>
                    <TouchableOpacity onPress={() => this.refs.drawer.openDrawer()}>
                        <Image source={LocalImg['searchIcon']}
                               style={{height: 30, width: 30, resizeMode: 'contain'}}/>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }

    renderBody() {
        return (
            <FlatList
                data={this.state.data}
                renderItem={(item, index) => this.renderRow(item, index)}
                keyExtractor={this.keyExtractor}
                ItemSeparatorComponent={this.separator}
                ListFooterComponent={() => this.footerView()}
                onEndReached={() => this.loadMore()}
                onEndReachedThreshold={0.1}
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.isLoading}
                        onRefresh={() => this.onRefresh()}
                    />
                }/>
        )

    }

    footerView() {
        return (
            <View style={{flexDirection: 'row', justifyContent: 'center', paddingTop: 20, paddingBottom: 30}}>
                <Text>到底了</Text>
            </View>
        )
    }

    loadMore() {
        if (!this.state.isLoading && this.isLoadMore) {
            this.loadData();
        }
    }


    onRefresh() {
        this.pageNum = 1;
        this.setState({
            data: [],
        });
        this.isLoadMore = true;
        this.loadData();
    }


    loadData() {
        this.setState({
            isLoading: true
        });
        const request = new Map();
        request.set('shzt', this.state.shzt);
        request.set('pageNum', this.pageNum);
        fetch(getRealUrl(Urls['ckjlUrl'], request), {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json"
            },
        })
            .then(response => response.json())
            .then(responseJson => {
                if (responseJson instanceof Array) {
                    this.setState({
                        data: this.state.data.concat(responseJson),
                    });

                    if (responseJson.length > 0) {
                        this.pageNum = this.pageNum +1;
                    } else {
                        this.isLoadMore = false;
                    }
                }
                this.setState({
                    isLoading: false
                })
            })
            .catch(error => {
                console.error(error);
                this.setState({
                    isLoading: false
                });
                this.isLoadMore = true;
            });

    }


    renderSlideBar() {

        return (
            <View style={{flexDirection: 'column', height: height - 60, backgroundColor: '#ffffff'}}>
                <List>
                    <InputItem labelNumber={5} placeholder="" value={this.state.zwcm}
                               onChange={(text) => this.setState({zwcm: text})}>中文船名</InputItem>
                    <InputItem labelNumber={5} placeholder="" value={this.state.ywcm}
                               onChange={(text) => this.setState({ywcm: text})}>英文船名</InputItem>
                    <InputItem labelNumber={5} placeholder="" value={this.state.hh}
                               onChange={(text) => this.setState({hh: text})}>呼号</InputItem>
                    <InputItem labelNumber={5} placeholder="" value={this.state.imo}
                               onChange={(text) => this.setState({imo: text})}>IMO</InputItem>
                    <InputItem labelNumber={5} placeholder="" value={this.state.mmsi}
                               onChange={(text) => this.setState({mmsi: text})}>MMSI</InputItem>
                    <View style={{margin: 12}}>
                        <Button type="primary" onClick={() => this.searchBoat()}>查询</Button>
                    </View>
                </List>
            </View>
        )
    }


    searchBoat() {
        this.pageNum = 1;
        this.setState({
            isLoading: true,
            data: [],
        });
        this.refs.drawer.closeDrawer();
        const request = new Map();

        if (this.state.zwcm !== '') {
            request.set("zwcm", this.state.zwcm);
        }

        if (this.state.ywcm !== '') {
            request.set("ywcm", this.state.ywcm);
        }

        if (this.state.hh !== '') {
            request.set("hh", this.state.hh);
        }

        if (this.state.imo !== '') {
            request.set("imo", this.state.imo);
        }

        if (this.state.mmsi !== '') {
            request.set("mmsi", this.state.mmsi);
        }

        fetch(getRealUrl(Urls['ckjlUrl'], request), {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json"
            },
        })
            .then(response => response.json())
            .then(responseJson => {

                if (responseJson instanceof Array) {
                    this.setState({
                        data: this.state.data.concat(responseJson),
                    });

                    if (responseJson.length > 0) {
                        this.pageNum = this.pageNum +1;
                    } else {
                        this.isLoadMore = false;
                    }
                }
                this.setState({
                    isLoading: false
                })
            })
            .catch(error => {
                console.error(error);
                this.setState({
                    isLoading: false
                });
                this.isLoadMore = true;
            });
    }

    keyExtractor = (item, index) => item.INNO + "";

    separator(index) {
        return (
            <View key={index} style={{height: 1, backgroundColor: '#CCCCCC'}}/>
        )
    }

    processDateTime(date) {
        const m = moment(date)
        if (m.isValid()) {
            return m.format('DD/HHmm')
        } else
            return ""
    }

    renderRow({item, index}) {

        return (
            <TouchableHighlight key={item.ID} onPress={() => this.enterDetail(index)}>
                <View style={styles.row}>
                    <Text style={[styles.text, {fontWeight: 'bold'}]}>
                        {item.VCVESCNAME} {item.VCVESENAME}
                    </Text>
                    <View style={{flexDirection: 'row'}}>
                        <Text style={styles.text}>
                            {'船籍:'}{item.VCNATIONNAME}
                        </Text>
                        <Text style={styles.text}>
                            {"呼号:"}{item.CHCALLNO}
                        </Text>
                    </View>
                </View>
            </TouchableHighlight>
        )
    }

    enterDetail(index) {
        this.props.navigation.navigate('PageCkjlDetail', {
            model: this.state.data[index]
        })
    }

}

const styles = StyleSheet.create({
    phone: {
        flex: 1,
        textDecorationLine: 'underline',
        color: '#0066FF',
    },
    text: {
        flex: 1
    },
    row: {
        flexDirection: 'column',
        justifyContent: 'center',
        padding: 10,
    },
});
export default PageCkjl;